package com.crazyauntzhang.easyshopbackend.controller;

import com.crazyauntzhang.easyshopbackend.domain.User;
import com.crazyauntzhang.easyshopbackend.request.LoginRequest;
import com.crazyauntzhang.easyshopbackend.result.ResponseResult;
import com.crazyauntzhang.easyshopbackend.service.LoginService;
import com.crazyauntzhang.easyshopbackend.util.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

	private final LoginService loginService;

	@Autowired
	public LoginController(LoginService loginService) {
		this.loginService = loginService;
	}

	/**
	 * 登录
	 *
	 * @param loginRequest 登录请求体类
	 * @return 【登录成功】【用户不存在】【用户不在职】
	 */
	@PostMapping("/login")
	public ResponseResult<Object> login(@RequestBody LoginRequest loginRequest) {
		//从请求体对象获取登录账号与登录密码
		String userID = loginRequest.getUserID();
		String password = loginRequest.getPassword();
		//搜索用户
		User loginUser = loginService.login(userID, password);
		//如果用户不存在，则返回响应体，提示用户不存在
		//如果用户存在，则进一步判断是否为在职员工，并构造响应体
		if (loginUser == null) {
			return new ResponseResult<>(10404, "LoginUser Not Found");
		} else {
			//构造响应体
			Map<String, Object> loginUserMap = new HashMap<>();
			loginUserMap.put("userID", loginUser.getUserID());
			loginUserMap.put("username", loginUser.getUsername());
			loginUserMap.put("roleID", loginUser.getRoleID());
			if (loginUser.getIsOnJob()) {
				//构造token
				Map<String, Object> claimsMap = new HashMap<>();
				claimsMap.put("userID", loginUser.getUserID());
				claimsMap.put("username", loginUser.getUsername());
				claimsMap.put("roleID", loginUser.getRoleID());
				String token = Token.createToken(claimsMap);
				loginUserMap.put("accessToken", token);
				return new ResponseResult<>(10200, "OK", loginUserMap);
			} else {
				return new ResponseResult<>(10410, "LoginUser Not OnJob", loginUserMap);
			}
		}
	}

}
